// pkg/conn/connection.go
package demo

import (
	"net"
	"sync"
	"tcp-lib/pkg/codec"
	"tcp-lib/pkg/router"
)

type Session struct {
	data sync.Map
}

func (s *Session) Set(key, value interface{}) {
	s.data.Store(key, value)
}

func (s *Session) Get(key interface{}) (interface{}, bool) {
	return s.data.Load(key)
}

type TCPConn struct {
	net.Conn
	Codec   codec.Codec
	Router  *router.Router
	Session Session
}

func NewTCPConn(c net.Conn, codec codec.Codec, router *router.Router) *TCPConn {
	return &TCPConn{
		Conn:    c,
		Codec:   codec,
		Router:  router,
		Session: Session{},
	}
}

func (c *TCPConn) Process() error {
	for {
		buf := make([]byte, 4096)
		n, err := c.Read(buf)
		if err != nil {
			return err
		}

		msg, err := c.Codec.Decode(buf[:n])
		if err != nil {
			return err
		}

		// 假设消息结构实现了ProtocolID方法
		if m, ok := msg.(interface{ GetProtocolID() uint32 }); ok {
			if handler, ok := c.Router.GetHandler(m.GetProtocolID()); ok {
				go handler(msg) // 高并发处理
			}
		}
	}
}
